// pages/users/coupon/index.js
const {
  couponList,
  couponReceive,
  couponReceiveList,
} = require('../../../api/api')

function time(val, option) {
  const a1 = val.split(' ')
  return a1[0]
}
const {
  message
} = require('../../../utils/util')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    list: [{
      status: 0,
      num: 50
    }, {
      status: 0,
      num: 10
    }, {
      status: 0,
      num: 5
    }, {
      status: 0,
      num: 30
    }],
    navList: [{
      name: '待领取'
    }, {
      status: 0,
      name: '未使用'
    }, {
      status: 1,
      name: '已使用'
    }],
    tabIndex: 0,
    status: 0,
    pageNo: 1,
    pageSize: 20,
    receiveList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    this.getReceiveList()
    this.getList()
  },
  //我的优惠券
  async getList(page) {
    if (page) {
      this.setData({
        pageNo: page,
        list: []
      })
    }
    const {
      list,
      pageNo,
      pageSize,
      status
    } = this.data
    const params = {
      pageNo,
      pageSize,
      status
    }
    const {
      result
    } = await couponList(params)

    if (result.records.length == 0) return
    result.records.map((item) => {
      item.endTime = time(item.endTime)
    })
    this.setData({
      list: list.concat(result.records),
      pageNo: pageNo + 1,
      total: result.total
    })
  },
  // 待领取优惠券
  async getReceiveList() {
    const {
      result
    } = await couponReceiveList()
    result.map((item) => {
      item.receiveEndTime = time(item.receiveEndTime)
    })
    this.setData({
      receiveList: result
    })
  },
  async receive(e) {
    const {
      id
    } = e.currentTarget.dataset
    this.setData({
      couponId: id
    })
    const tempIds = ['eLyBtNKEEv1u9H-AYCnmvOyD8poAycD4awzaz-GcimA']
    let self = this;
    message(false, tempIds, '', self.callback.bind(self))

  },
  async callback() {
    const params = {
      couponId: this.data.couponId
    }
    const result = await couponReceive(params)
    if (result.success) {
      wx.showToast({
        title: result.message,
        icon: 'none'
      })
      this.getReceiveList()
      // this.getList(1)
    }
  },
  changeIndex(e) {
    const {
      index,
      type,
      status
    } = e.currentTarget.dataset
    this.setData({
      [type]: parseInt(index),
      list: [],
      status
    })
    if (index == 0) return
    this.getList(1)

  },
  goto(e) {
    wx.navigateTo({
      url: '/pages/article/vip/index',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

})